import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/components/Home.vue'
import storage from './../utils/storage'
import API from './../api'
import utils from './../utils/utils'

const routes = [
	{
		name: 'home',
		path: '/',
		meta: {
			title: '首页'
		},
		component: Home,
		redirect: '/welcome',
		children: [
			{
				name: 'welcome',
				path: '/welcome',
				meta: {
					title: '欢迎体验'
				},
				component: () => import('@/views/Welcome.vue')
			},
			{
				name: 'dashboard',
				path: '/dashboard',
				meta: {
					title: '数据报表'
				},
				component: () => import('@/views/DashBoard.vue')
			},
			{
				name: 'approve',
				path: '/approve',
				meta: {
					title: 'approve'
				},
				component: () => import('@/views/Approve.vue')
			},
			{
				name: 'dept',
				path: '/dept',
				meta: {
					title: 'dept'
				},
				component: () => import('@/views/Dept.vue')
			},
			{
				name: 'leave',
				path: '/leave',
				meta: {
					title: 'leave'
				},
				component: () => import('@/views/Leave.vue')
			},
			{
				name: 'menu',
				path: '/menu',
				meta: {
					title: ''
				},
				component: () => import('@/views/Menu.vue')
			},
			{
				name: 'role',
				path: '/role',
				meta: {
					title: ''
				},
				component: () => import('@/views/Role.vue')
			},
			{
				name: 'user',
				path: '/user',
				meta: {
					title: ''
				},
				component: () => import('@/views/User.vue')
			}
		]
	},
	{
		name: 'login',
		path: '/login',
		meta: {
			title: '登录'
		},
		component: () => import('@/views/Login.vue')
	},
	{
		name: '404',
		path: '/404',
		meta: {
			title: '页面不存在'
		},
		component: () => import('@/views/404.vue')
	}
]

const router = createRouter({
	history: createWebHashHistory(),
	routes
})

async function loadAsyncRoutes() {
	let userInfo = storage.getItem('userInfo') || {}
	if (userInfo.token) {
		try {
			const { menuList } = await API.getPermissionList()
			let routes = utils.generateRoute(menuList)
			console.log('routes--------->', routes)
			routes.map((route) => {
				let url = `@/views/${route.component}.vue`
				route.component = () => import(url)
				router.addRoute('home', route)
			})

			// 导航守卫
			router.beforeEach((to, from, next) => {
				if (router.hasRoute(to.name)) {
					document.title = to.meta.title
					next()
				} else {
					next('/404')
				}
			})
		} catch (error) {}
	}
}
loadAsyncRoutes()
// 判断当前地址是否可以访问
/*
function checkPermission(path) {
	let hasPermission = router.getRoutes().filter(route => route.path == path).length;
	if (hasPermission) {
			return true;
	} else {
			return false;
	}
}
*/

export default router
